﻿using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

namespace DeploySources.Helper
{
	/// <summary>
	/// Connection Serializer to XML
	/// </summary>
	public class ConnectionSerializer
	{
		private static readonly string ConnectionFile = "connections.xml";

		/// <summary>
		/// Serialize the Connectio Items to a file
		/// </summary>
		/// <param name="connectionItems">Items to serialize</param>
		public static void Serialize(List<ConnectionItem> connectionItems)
		{
			var serializer = new XmlSerializer(connectionItems.GetType());
			using (var writer = XmlWriter.Create(ConnectionFile))
			{
				serializer.Serialize(writer, connectionItems);
			}

		}

		/// <summary>
		/// Reads the connections and deserializes them
		/// </summary>
		/// <returns>Returns the deserialized items</returns>
		public static List<ConnectionItem> Deserialize()
		{
			var serializer = new XmlSerializer(typeof(List<ConnectionItem>));

			if (!System.IO.File.Exists(ConnectionFile))
			{
				Serialize(new List<ConnectionItem>());
			}

			using (var reader = XmlReader.Create(ConnectionFile))
			{
				return (List<ConnectionItem>)serializer.Deserialize(reader);
			}
		}
	}
}
